import Immutable from 'immutable'
import { Button, message, Popover, Modal } from 'antd'
import { WeaRichText } from 'ecCom'
import * as Util from '../../util/transf'

const confirm = Modal.confirm;

export default class ReplyItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      value: '',
      status: '',
      operate: '',
    }
    this.onToolsChange = this.onToolsChange.bind(this);
  }
  render() {
    let { data, extentsConfig, onRichSubmit, isLast, getMoreReplyMain, getMoreReplyChild } = this.props,
      { visible, value, status, operate } = this.state,
      hasMore = 0,
      lastChild = Immutable.fromJS({});
    return (
      <div className='wea-doc-detail-reply-list-item' style={ data.get('children').size === 0 && !visible ? { paddingBottom: 0 } : {}}>
        { this.getChild(data, 0) }
        <div className='wea-doc-detail-reply-list-item-children' style={data.get('children').size === 0 && !visible ? { border: 0 } : {}}>
          {
            data.get('children').map((child, i) => {
              hasMore = data.get('children').size === i + 1 && child.get('ishave');
              if(hasMore) lastChild = child;
              return this.getChild(child, 1)
            })
          }
          {
            visible && 
            <div className='wea-doc-detail-reply-list-item-child' style={{padding: 0, borderTopStyle: 'solid'}}>
              <WeaRichText
                id={data.get('replyid')}
                value={value}
                ckConfig={{
                  toolbar:[
                    { name: 'document', items: [ 'Source'] },
                    { name: 'paragraph', items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList' ] },
                    { name: 'styles', items: [ 'Format', 'Font', 'FontSize' ] },
                    { name: 'colors', items: [ 'TextColor' ] },
                    { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', ] },
                    { name: 'links', items: [ 'Link', 'Unlink' ] },
                    { name: 'insert', items: [ 'Image', 'Table', 'Smiley'] },
                    { name: 'clipboard', items: [ 'Undo', 'Redo' ] },
                  ],
                  height:100,
                  uploadUrl: '/api/doc/upload/uploadFile?model=reply',
                }}
                extentsConfig={extentsConfig}
                onChange={v=>this.setState({value: v})}
                onStatusChange={s =>this.setState({status: s})}
                onToolsChange={this.onToolsChange}
              />
              {
                status === 'ready' &&
                <div className='wea-doc-detail-reply-rich-btm'>
                  <Button type='primary' onClick={()=>{
                    if(value) {
                      let { Upload_image, Upload_file, Browser_152, Browser_37 } = this.state;
                      typeof onRichSubmit === 'function' && onRichSubmit({content: value, replyid: data.get('replyid'), operate }, hasMore ? { replymainid: lastChild.get('replymainid'), lastreplyid: lastChild.get('replyid') } : 0, Upload_image, Upload_file, Browser_152, Browser_37)
                      this.setState({value: '',visible: false})
                    }else{
                      message.warning('回复内容不能为空！')
                    }
                  }}>提交</Button>
                  <Button type='ghost' style={{marginLeft: 8}} onClick={()=>this.setState({value: '',visible: false})}>取消</Button>
                </div>
              }
            </div>
          }
          {
            hasMore ? <div className='wea-doc-detail-reply-list-item-child' style={{padding: '10px 0', textAlign: 'center'}}>
              { `还有 ${lastChild.get('residue')} 条回复，  ` }
              <a href='javaScript:void(0)' style={{ color: '#4d7ad8' }}  onClick={()=> {
                typeof getMoreReplyChild === 'function' && getMoreReplyChild({ replymainid: lastChild.get('replymainid'), lastreplyid: lastChild.get('replyid') })
              }} >点击查看</a>
            </div>
            : null
          }
        </div>
         {
          isLast && data.get('ishave') ? <div style={{padding: '10px 0', marginTop: 10, textAlign: 'center', border: '1px solid #e8e8e8', borderWidth: '1px 0'}}>
            <a href='javaScript:void(0)' style={{ color: '#4d7ad8' }} onClick={()=> {
              typeof getMoreReplyMain === 'function' && getMoreReplyMain({ lastreplyid: data.get('replyid'), orderby: 'desc' })
            }} >加载更多</a>
          </div>
          : null
        }
      </div>
    )
  }
  getChild(data, isChild){
    let { onPraiseClick, deleteReply } = this.props,
      hasPraise = data.get('praiseInfo'),
      praise = 0,
      isPraise = 0,
      users = Immutable.fromJS([]),
      showTime = Util.transfTime(data.get('rdata'),data.get('rtime')).split(' ');
    if(hasPraise){
      praise = hasPraise.get('users').size;
      isPraise = hasPraise.get('isPraise');
      users = hasPraise.get('users');
    }
    return (
      <div className='wea-doc-detail-reply-list-item-child' style={ data.get('children') ? { border: 0 } : (isChild ? { padding: 10 } : {})}>
        {
          !isChild && <span className='wea-doc-detail-reply-list-item-child-img' dangerouslySetInnerHTML={{__html: data.get('handImg')}}/>
        }
        <div>
          <p className='wea-doc-detail-reply-list-item-child-title'>
            <span style={{ marginRight: isChild ? 7 : 12 }} dangerouslySetInnerHTML={{ __html: `<a href='javaScript:openhrm(${data.get('userid')});' onclick='pointerXY(event);' style='color: #4d7ad8;'>${data.get('username')}</a>` }} />
            {
              isChild ? <span style={{ marginRight: 4, color: '#484a4d' }}>回复</span> : null
            }
            {
              isChild ? <span dangerouslySetInnerHTML={{ __html: `<a href='javaScript:openhrm(${data.get('ruserid')});' onclick='pointerXY(event);' style='color: #4d7ad8;'>${data.get('rusername')}</a>` }} /> : null
            }
            {
              showTime.length === 2 ? <span>{data.get('rdata')}</span> : null
            }
            {
              showTime.length === 2 ? <span>{data.get('rtime')}</span> : null
            }
            {
              showTime.length === 1 ? <span>{showTime[0]}</span> : null
            }
          </p>
          <div dangerouslySetInnerHTML={{__html: data.get('content')}}/>
          <span className='wea-doc-detail-reply-list-item-child-ops'>
            <span onClick={() => this.setState({visible: true, value: data.get('content'), operate: 'edit'})}><i className='icon-coms-edit' />修改</span>
            <span onClick={() => {
              confirm(
                {
                  content: '确认要删除这条回复吗？',
                  onOk() {
                    typeof deleteReply === 'function' && deleteReply({ replyid: data.get('replyid'), parentid: data.get('replymainid') })
                  }
                }
              )
            }}><i className='icon-coms-delete' />删除</span>
            <span onClick={() => this.setState({visible: true, value: '', operate: 'save'})}><i className='icon-coms-New-SMS' />回复</span>
            <span>
              <i className='icon-coms-Good' style={ isPraise ? {color: '#ff602f'} : null} onClick={()=>{ typeof onPraiseClick === 'function' && onPraiseClick(data, !isPraise) }}/>
              <Popover overlayClassName="wea-doc-detail-top-reply-count-wrap wea-doc-detail-top-reply-count-wrap-right" placement="bottomRight" content={
                users.size > 0 ?
                  <span>
                    {
                      users.map((user, index) => {
                        return (
                          <span><span dangerouslySetInnerHTML={{ __html: `<a href='javaScript:openhrm(${user.get('userid')});' onclick='pointerXY(event);' style='color: #fff;'>${user.get('userName')}</a>` }} />{users.size < index ? ', ' : ''}</span>
                        )
                      })
                    }
                  </span>
                : '还没有人点赞哦 ~'
              } 
              trigger="hover">
                <span style={ isPraise ? {color: '#ff602f'} : null} className='wea-doc-detail-top-reply-count'> ({praise})</span>
              </Popover>
            </span>
          </span>
        </div>
      </div>
    )
  }
  onToolsChange(name = '', ids = '', list = [], type = ''){
    let stateList = this.state[`${name}_${type}`],
      mirror = {
        37: "doc",
        152: "workflow",
      },
      newList = list.map(item => {
        let _item = { ...item };
        if(name === 'Upload' && type === 'image') {
          _item.string = `=${_item.fileid}`;
        }else if(name === 'Upload' && type === 'file') {
          _item.string = `=${_item.fileid}`;
        }else if(name === 'Browser') {
          _item.string = `,${item.id},`;
        }
        return _item
      });
    this.setState({ [`${name}_${type}`] : (stateList ? stateList.concat(newList) : newList) })
    return Util.transfStr(name, ids, list, type);
  }
}